package org.oschina.api.user.role.dao;

import java.util.ArrayList;
import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.manage.module.vo.ModuleVo;
import org.oschina.api.user.role.model.UserRole;
import org.oschina.api.user.role.vo.UserRoleVo;
import org.springframework.stereotype.Repository;

@Repository
public class UserRoleDAO extends BaseDAO {

	private final String findVo="SELECT ml.id as 'id',ml.name as 'name' FROM "+Constants.DB_USER_ROLE+" ur,"+Constants.DB_MODULE+" ml WHERE ur.module=ml.id";
	
	private final String findVoByRole=findVo+" AND ur.role=? AND ml.type=?";
	/**
	 * 根据角色和类型返回
	 * @param role
	 * @param type
	 * @return
	 */
	public List<ModuleVo> findVoByRoleAndType(int role,int type)
	{
		return getQueryHelper().query_cache(findVoByRole, new Object[]{role,type}, ModuleVo.class);
	}
	
	private final String findVoByRoleAndModule=findVo+" AND ur.role=? AND ur.module=?";
	/**
	 * 根据角色和模块返回
	 * @param role
	 * @param module
	 * @return
	 */
	public UserRoleVo findVoByRoleAndModule(int role,int module)
	{
		return (UserRoleVo) getQueryHelper().queryForObject_cache(findVoByRoleAndModule, new Object[]{role,module}, UserRoleVo.class);
	}
	
	/**
	 * 更新角色模块
	 * @param role
	 * @param type
	 * @param modules
	 * @return
	 */
	public boolean updateModuleByRole(int role,int type,List<UserRole> roles)
	{
		getQueryHelper().delete_cache(Constants.CACHE_MANAGE_MENU,Constants.DB_USER_ROLE, new String[]{"role=? AND module IN (SELECT ml.id FROM "+Constants.DB_MODULE+" ml WHERE ml.type=?)"}, new Object[]{role,type});
		getQueryHelper().delete_cache(Constants.CACHE_MODULE,null,null,null);
		
		if(roles!=null && !roles.isEmpty())
		{
			List<Object[]> args=new ArrayList<Object[]>(roles.size());
			for(UserRole temp:roles)
				args.add(new Object[]{temp.getId(),temp.getRole(),temp.getModule()});
			
			getQueryHelper().batchUpdate_cache(Constants.CACHE_USER_ROLE, "INSERT "+Constants.DB_USER_ROLE+"(id,role,module) VALUES(?,?,?)",args);
		}
		
		return true;
	}
	
	/**
	 * 根据角色删除
	 * @param role
	 * @return
	 */
	public int removeByRole(int role)
	{
		return (int) getQueryHelper().delete_cache(Constants.CACHE_MANAGE_MENU,Constants.DB_USER_ROLE, new String[]{"role=?"}, new Object[]{role});
	}
}